package com.dreamsky.life.controller;

import java.util.List;

import com.dreamsky.life.interceptor.LoginValidator;
import com.dreamsky.life.model.Electric;
import com.dreamsky.life.model.User;
import com.dreamsky.life.util.Const;
import com.dreamsky.life.util.StringUtils;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;

public class LoginController extends Controller {
	public void index() {

		String p = getRequest().getHeader("User-Agent");
		setAttr("basePath", StringUtils.basePath(getRequest()));

		String userId = getSessionAttr(Const.USER_ID_KEY);
		if (userId != null) {
			loginSuccess();
			return;
		}

		if (p.indexOf("Mobile") > 0) {
			renderJsp("WEB-INF/view/mobile.jsp");
		} else {
			renderJsp("WEB-INF/view/desktop.jsp");
		}

	}

	/**
	 * 
	 */
	@Before(LoginValidator.class)
	public void login() {
		User user = this.getModel(User.class).loginFind();

		if (user != null) {
			setSessionAttr(Const.USER_ID_KEY, user.getStr("id"));

			setAttr("success", true);
			setAttr("path", "loginSuccess");
			renderJson(new String[] { "success", "path" });
		} else {
			setAttr("success", false);
			setAttr("logerr", Const.LOGIN_NO_SUCCESS);

			renderJson(new String[] { "success", "logerr" });
		}

	}

	public void loginSuccess() {
		String userId = getSessionAttr(Const.USER_ID_KEY);
		if (userId == null) {
			index();
			return;
		}

		List<Electric> eleList = Electric.dao.userEletric(userId);

		setAttr("eleList", eleList);
		setAttr("basePath", StringUtils.basePath(getRequest()));

		renderJsp("WEB-INF/view/user.jsp");
	}

	public void logout() {
		if (getSession(false) != null)
			getSession(false).removeAttribute(Const.USER_ID_KEY);
		index();
	}
}
